package com.ruoyi.aitcommon.utils;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.config.LocalDBConfig;
import com.ruoyi.aitcommon.vo.DBConVO;
import com.ruoyi.common.utils.StringUtils;

/**
 * 版本2,使用Druid连接池
 * conn示例:
 * sqlserver:"jdbc:sqlserver://localhost:1433;databasename=XX";
 * oracle:"jdbc:oracle:thin:@localhost:1521:orcl"
 * mysql:"jdbc:mysql://localhost:3306/sqltestdb?serverTimezone=Asia/Shanghai"
 * 
 * @author Administrator
 */
public class DBUtils {
	public String driveClassName="";
	public String url="";
	public String user="";
	public String password="";
	public DBConVO dbCon=null;
	
	@Override
	public String toString() {
		return "DBUtils [driveClassName=" + driveClassName + ", url=" + url + ", user=" + user + ", password="
				+ password + "]";
	}
	/**
	 * 基于JSON配置信息构造DB链接
	 * @param dbjson
	 */
	public DBUtils(JSONObject dbjson) throws Exception {
		this(dbjson.getString("url"),dbjson.getString("username"),dbjson.getString("password"));
	}
	/**
	 * 基于yml配置文件,构造AIT本地链接
	 */
	public DBUtils() throws Exception {
		this("", "", "");
	}
	/**
	 * 指定数据库链接信息,构造DB链接
	 * @param url
	 * @param user
	 * @param password
	 */
	public DBUtils(String url, String user, String password) throws Exception {
		if (StringUtils.isBlank(url)) {
//			本地数据库配置
//			DBConfig为Spring配置类，通过静态化，可以在Utils类中直接使用
			url = LocalDBConfig.getUrl();
		}
		if (StringUtils.isBlank(user)) {
			user = LocalDBConfig.getUsername();
		}
		if (StringUtils.isBlank(password)) {
			password = LocalDBConfig.getPassword();
		}

		this.dbCon=new DBConVO();
		this.dbCon.setUrl(url);
		this.dbCon.setUsername(user);
		this.dbCon.setPassword(password);

		this.url=url;
		this.user=user;
		this.password=password;
		this.driveClassName=this.dbCon.getDriveClassName(url);
		
	}
	public DBConVO getDBConVO() {
		return this.dbCon;
	}
	public JSONObject getDBConJSON() {
		JSONObject json=(JSONObject) JSONObject.toJSON(this.dbCon);
		return json;
	}
	public Connection open() throws Exception {
//		从连接池中获取链接
//		不再缓存连接,每次都从连接池中获取新的链接
		return DruidUtils.getConnection(this.dbCon);
	}

}
